﻿using AutoMapper;
using MediatR;
using MySqlX.XDevAPI.Common;
using Return.Enum;
using SlaughterItem.Common.Infrastructures.Interfaces;
using THE_WIND_RISES.Common.Domans.Produce.Resources;
using THE_WIND_RISES.Common.Domans.Produce.Supplier;
using THE_WIND_RISES.Common.Dtos;

namespace Production_Set.API.Application.Commands.Supplier
{
    public class SupplierCreateHandler : IRequestHandler<SupplierCreateCommand, THE_WIND_RISES.Common.Dtos.Result>
    {
        /// <summary>
        /// 供应商仓储
        /// </summary>
        private readonly IBaseRepository<Suppliers> supplierRepository;
        /// <summary>
        /// 营业执照
        /// </summary>
        private readonly IBaseRepository<BusinessLicenses> businessLicensesRepository;
        /// <summary>
        /// 联系人信息
        /// </summary>
        private readonly IBaseRepository<ContactPersons> contactPersonsRepository;
        /// <summary>
        /// 银行信息
        /// </summary>
        private readonly IBaseRepository<Banks> banksRepository;
        /// <summary>
        /// 映射
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<SupplierCreateHandler> logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="supplierRepository"></param>
        /// <param name="mapper"></param>
        /// <param name="businessLicensesRepository"></param>
        /// <param name="contactPersonsRepository"></param>
        /// <param name="banksRepository"></param>
        /// <param name="logger"></param>
        public SupplierCreateHandler(IBaseRepository<Suppliers> supplierRepository, IMapper mapper, IBaseRepository<BusinessLicenses> businessLicensesRepository, IBaseRepository<ContactPersons> contactPersonsRepository, IBaseRepository<Banks> banksRepository, ILogger<SupplierCreateHandler> logger)
        {
            this.supplierRepository = supplierRepository;
            this.mapper = mapper;
            this.businessLicensesRepository = businessLicensesRepository;
            this.contactPersonsRepository = contactPersonsRepository;
            this.banksRepository = banksRepository;
            this.logger = logger;
        }
        /// <summary>
        /// 业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<THE_WIND_RISES.Common.Dtos.Result> Handle(SupplierCreateCommand request, CancellationToken cancellationToken)
        {
            var result = new THE_WIND_RISES.Common.Dtos.Result() { Code = (int)CommonErrorCodes.Added };

            try
            {
                string SuppliersSql = $"select * from Suppliers where SuppliersNo='{request.SuppliersNo}'";
                var SuppliersList = supplierRepository.GetAll(SuppliersSql).FirstOrDefault();
                if (SuppliersList != null)
                {
                    result.Code = (int)CommonErrorCodes.Added;
                    result.Data = null;
                    result.Msg = "编号重复 请重新输入";
                    logger.LogError("添加失败 编号重复 请重新输入");

                    foreach (var item in request.BusinessLicensesData)
                    {
                        var BusinessLicensesSql = "insert into BusinessLicenses values(@BusinessLicenseId,@BusinessLicenseNo,@Representative,@EnterpriseTypeId,@BusinessLicensesRange,@BusinessLicensesDate,@BusinessLicensesStateser,@SuppliersId,@Handle,@HandleContext,@HandleTime,@Pid,@IsDelete);";
                        string SuppliersSql2 = $"select * from Suppliers  where SuppliersId={SuppliersList.SuppliersId}";
                        var AddBusinessLicensesNum = businessLicensesRepository.Add(BusinessLicensesSql, new
                        {
                            BusinessLicenseId = 0,
                            BusinessLicenseNo = item.BusinessLicenseNo,
                            Representative = item.Representative,
                            EnterpriseTypeId = item.EnterpriseTypeId,
                            BusinessLicensesRange = item.BusinessLicensesRange,
                            BusinessLicensesDate = item.BusinessLicensesDate,
                            BusinessLicensesStateser = item.BusinessLicensesStateser,
                            SuppliersId = SuppliersList.SuppliersId,
                            Handle = request.Handle,
                            HandleContext = request.HandleContext,
                            HandleTime = DateTime.Now,
                            Pid = request.Pid,
                            IsDelete = request.IsDelete
                        });
                    }
                    foreach (var item in request.ContactPersonsData)
                    {
                        var ContactPersonsSql = "insert into ContactPersons values(@ContactPersonsId,@ContactPersonsName,@ContactPersonsTell,@Position,@ContactPersonStatus,@SuppliersId,@IsDelete,@Handle,@HandleContext,@HandleTime,@Pid);";
                        string SuppliersSql2 = $"select * from Suppliers  where SuppliersId={SuppliersList.SuppliersId}";
                        var AddContactPersonsNum = contactPersonsRepository.Add(ContactPersonsSql, new
                        {
                            ContactPersonsId = 0,
                            ContactPersonsName = item.ContactPersonsName,
                            ContactPersonsTell = item.ContactPersonsTell,
                            Position = item.Position,
                            ContactPersonStatus = item.ContactPersonStatus,
                            SuppliersId = SuppliersList.SuppliersId,
                            Handle = request.Handle,
                            HandleContext = request.HandleContext,
                            HandleTime = DateTime.Now,
                            Pid = request.Pid,
                            IsDelete = request.IsDelete
                        });
                    }
                    foreach (var item in request.BanksData)
                    {
                        var BanksSql = "insert into Banks values(@BanksId,@BanksNo,@BranchNo,@BanksAccount,@BankStatus,@SuppliersId,@IsDelete,@Handle,@HandleContext,@HandleTime,@Pid);";
                        string SuppliersSql2 = $"select * from Suppliers  where SuppliersId={SuppliersList.SuppliersId}";
                        var AddBanksNum = banksRepository.Add(BanksSql, new
                        {
                            BanksId = 0,
                            BanksNo = item.BanksNo,
                            BranchNo = item.BranchNo,
                            BanksAccount = item.BanksAccount,
                            BankStatus = item.BankStatus,
                            SuppliersId = SuppliersList.SuppliersId,
                            Handle = request.Handle,
                            HandleContext = request.HandleContext,
                            HandleTime = DateTime.Now,
                            Pid = request.Pid,
                            IsDelete = request.IsDelete
                        });
                    }
                    return result;
                }
                else
                {
                    var AddData = mapper.Map<Suppliers>(request);
                    SuppliersSql = "insert into Suppliers values(@SuppliersId,@SuppliersNo,@SuppliersName,@SuppliersType,@SuppliersPhone,@SuppliersAdder,@CountryId,@CityId,@SupplierClassification,@SupplierLabels,@CompanyLogo,@OutsideLabel,@SuppliersStatus,@IsDelete,@Handle,@HandleContext,@HandleTime,@Pid);";
                    var AddNum = supplierRepository.Add(SuppliersSql, new
                    {
                        SuppliersId = AddData.SuppliersId,
                        SuppliersNo = AddData.SuppliersNo,
                        SuppliersName = AddData.SuppliersName,
                        SuppliersType = AddData.SuppliersType,
                        SuppliersPhone = AddData.SuppliersPhone,
                        SuppliersAdder = AddData.SuppliersAdder,
                        CountryId = AddData.CountryId,
                        CityId = AddData.CityId,
                        SupplierClassification = AddData.SupplierClassification,
                        SupplierLabels = AddData.SupplierLabels,
                        CompanyLogo = AddData.CompanyLogo,
                        OutsideLabel = AddData.OutsideLabel,
                        SuppliersStatus = AddData.SuppliersStatus,
                        Handle = request.Handle,
                        HandleContext = request.HandleContext,
                        HandleTime = DateTime.Now,
                        Pid = request.Pid,
                        IsDelete = AddData.IsDelete
                    });
                    if (AddNum > 0)
                    {
                        string SuppliersSql1 = $"select * from Suppliers where SuppliersNo='{request.SuppliersNo}'";
                        SuppliersList = supplierRepository.GetAll(SuppliersSql1).FirstOrDefault();

                        var data = new
                        {
                            SuppliersId = SuppliersList.SuppliersId
                        };
                        foreach (var item in request.BusinessLicensesData)
                        {
                            var BusinessLicensesSql = "insert into BusinessLicenses values(@BusinessLicenseId,@BusinessLicenseNo,@Representative,@EnterpriseTypeId,@BusinessLicensesRange,@BusinessLicensesDate,@BusinessLicensesStateser,@SuppliersId,@Handle,@HandleContext,@HandleTime,@Pid,@IsDelete);";
                            string SuppliersSql2 = $"select * from Suppliers  where SuppliersId={SuppliersList.SuppliersId}";
                            var AddBusinessLicensesNum = businessLicensesRepository.Add(BusinessLicensesSql, new
                            {
                                BusinessLicenseId = 0,
                                BusinessLicenseNo = item.BusinessLicenseNo,
                                Representative = item.Representative,
                                EnterpriseTypeId = item.EnterpriseTypeId,
                                BusinessLicensesRange = item.BusinessLicensesRange,
                                BusinessLicensesDate = item.BusinessLicensesDate,
                                BusinessLicensesStateser = item.BusinessLicensesStateser,
                                SuppliersId = SuppliersList.SuppliersId,
                                Handle = request.Handle,
                                HandleContext = request.HandleContext,
                                HandleTime = DateTime.Now,
                                Pid = request.Pid,
                                IsDelete = request.IsDelete
                            });
                        }
                        foreach (var item in request.ContactPersonsData)
                        {
                            var ContactPersonsSql = "insert into ContactPersons values(@ContactPersonsId,@ContactPersonsName,@ContactPersonsTell,@Position,@ContactPersonStatus,@SuppliersId,@IsDelete,@Handle,@HandleContext,@HandleTime,@Pid);";
                            string SuppliersSql2 = $"select * from Suppliers  where SuppliersId={SuppliersList.SuppliersId}";
                            var AddContactPersonsNum = contactPersonsRepository.Add(ContactPersonsSql, new
                            {
                                ContactPersonsId = 0,
                                ContactPersonsName = item.ContactPersonsName,
                                ContactPersonsTell = item.ContactPersonsTell,
                                Position = item.Position,
                                ContactPersonStatus = item.ContactPersonStatus,
                                SuppliersId = SuppliersList.SuppliersId,
                                Handle = request.Handle,
                                HandleContext = request.HandleContext,
                                HandleTime = DateTime.Now,
                                Pid = request.Pid,
                                IsDelete = request.IsDelete
                            });
                        }
                        foreach (var item in request.BanksData)
                        {
                            var BanksSql = "insert into Banks values(@BanksId,@BanksNo,@BranchNo,@BanksAccount,@BankStatus,@SuppliersId,@IsDelete,@Handle,@HandleContext,@HandleTime,@Pid);";
                            string SuppliersSql2 = $"select * from Suppliers  where SuppliersId={SuppliersList.SuppliersId}";
                            var AddBanksNum = banksRepository.Add(BanksSql, new
                            {
                                BanksId = 0,
                                BanksNo = item.BanksNo,
                                BranchNo = item.BranchNo,
                                BanksAccount = item.BanksAccount,
                                BankStatus = item.BankStatus,
                                SuppliersId = SuppliersList.SuppliersId,
                                Handle = request.Handle,
                                HandleContext = request.HandleContext,
                                HandleTime = DateTime.Now,
                                Pid = request.Pid,
                                IsDelete = request.IsDelete
                            });
                        }

                        result.Code = (int)CommonErrorCodes.Success;
                        result.Data = null;
                        result.Msg = "供应商添加成功";
                        logger.LogInformation("供应商添加成功");
                    }
                }
            }
            catch (Exception ex)
            {
                logger.LogError("供应商添加失败" +ex.Message);

                throw;
            }

            return result;
        }

       

    }
}
